<template>
  <div class="session-list-container">
    <div 
      v-for="session in chatStore.sessions" 
      :key="session.sessionId"
      :class="['session-item', { active: session.sessionId === chatStore.currentSessionId }]"
      @click="selectSession(session.sessionId)"
    >
      <div class="session-info">
        <div class="session-title">{{ session.title || '未命名对话' }}</div>
        <div class="session-meta">
          <span class="message-count">{{ session.messageCount || 0 }}条消息</span>
          <span class="last-time">{{ formatTime(session.lastActiveTime) }}</span>
        </div>
      </div>
      
      <div class="session-actions" @click.stop>
        <el-dropdown @command="handleAction" trigger="click">
          <el-button text size="small" class="action-btn">
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="{ action: 'rename', session }">
                <el-icon><Edit /></el-icon>重命名
              </el-dropdown-item>
              <el-dropdown-item :command="{ action: 'archive', session }">
                <el-icon><FolderOpened /></el-icon>归档
              </el-dropdown-item>
              <el-dropdown-item 
                :command="{ action: 'delete', session }"
                style="color: #f56c6c;"
              >
                <el-icon><Delete /></el-icon>删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="chatStore.sessions.length === 0" class="empty-state">
      <el-empty 
        description="暂无对话会话" 
        :image-size="80"
      >
        <template #description>
          <p>点击"新建对话"开始与AI聊天</p>
        </template>
      </el-empty>
    </div>
  </div>

  <!-- 重命名对话框 -->
  <el-dialog
    v-model="showRenameDialog"
    title="重命名对话"
    width="400px"
    :before-close="handleCloseRename"
  >
    <el-form @submit.prevent="confirmRename">
      <el-form-item label="对话标题">
        <el-input 
          v-model="newTitle" 
          placeholder="请输入新的对话标题"
          @keyup.enter="confirmRename"
          ref="titleInput"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showRenameDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmRename" :loading="renameLoading">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 会话列表组件
 * 显示用户的所有对话会话，支持选择、重命名、删除等操作
 */
import { ref, nextTick } from 'vue'
import { useChatStore } from '@/stores/chat'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled, Edit, FolderOpened, Delete } from '@element-plus/icons-vue'

const chatStore = useChatStore()

// 重命名相关
const showRenameDialog = ref(false)
const newTitle = ref('')
const currentRenameSession = ref(null)
const renameLoading = ref(false)
const titleInput = ref(null)

/**
 * 选择会话
 */
const selectSession = async (sessionId) => {
  if (sessionId === chatStore.currentSessionId) return
  
  const response = await chatStore.selectSession(sessionId)
  if (!response.success) {
    ElMessage.error(response.message || '选择会话失败')
  }
}

/**
 * 格式化时间显示
 */
const formatTime = (timeString) => {
  if (!timeString) return ''
  
  const time = new Date(timeString)
  const now = new Date()
  const diff = now - time
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于1天
  else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 大于1天
  else {
    return time.toLocaleDateString()
  }
}

/**
 * 处理会话操作
 */
const handleAction = async ({ action, session }) => {
  switch (action) {
    case 'rename':
      currentRenameSession.value = session
      newTitle.value = session.title || ''
      showRenameDialog.value = true
      // 等待对话框渲染完成后聚焦输入框
      nextTick(() => {
        titleInput.value?.focus()
        titleInput.value?.select()
      })
      break
      
    case 'archive':
      try {
        const archiveResponse = await chatStore.archiveSession(session.sessionId)
        if (archiveResponse.success) {
          ElMessage.success('会话已归档')
          await chatStore.loadUserSessions() // 刷新列表
        } else {
          ElMessage.error(archiveResponse.message || '归档失败')
        }
      } catch (error) {
        ElMessage.error('归档操作失败')
      }
      break
      
    case 'delete':
      try {
        await ElMessageBox.confirm(
          `确定要删除对话"${session.title || '未命名对话'}"吗？此操作不可恢复。`,
          '确认删除',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger'
          }
        )
        
        const deleteResponse = await chatStore.deleteSession(session.sessionId)
        if (deleteResponse.success) {
          ElMessage.success('会话已删除')
        } else {
          ElMessage.error(deleteResponse.message || '删除失败')
        }
      } catch {
        // 用户取消删除
      }
      break
  }
}

/**
 * 确认重命名
 */
const confirmRename = async () => {
  // 参数验证
  const trimmedTitle = newTitle.value?.trim()
  
  if (!trimmedTitle || trimmedTitle.length === 0) {
    ElMessage.warning('请输入有效的对话标题')
    titleInput.value?.focus()
    return
  }
  
  if (!currentRenameSession.value?.sessionId) {
    ElMessage.error('会话信息无效，请刷新页面重试')
    showRenameDialog.value = false
    return
  }
  
  // 🔧 添加调试日志确保值正确传递
  console.log('准备发送标题', trimmedTitle)
  
  renameLoading.value = true
  try {
    const response = await chatStore.renameSession(
      currentRenameSession.value.sessionId, 
      trimmedTitle
    )
    
    if (response && response.success) {
      ElMessage.success('重命名成功')
      showRenameDialog.value = false
      // 重置状态
      newTitle.value = ''
      currentRenameSession.value = null
    } else {
      ElMessage.error(response?.message || '重命名失败，请稍后重试')
    }
  } catch (error) {
    console.error('重命名操作异常:', error)
    ElMessage.error('重命名操作失败，请检查网络连接')
  } finally {
    renameLoading.value = false
  }
}

/**
 * 处理重命名对话框关闭
 */
const handleCloseRename = (done) => {
  if (renameLoading.value) {
    ElMessage.warning('正在处理中，请稍候...')
    return
  }
  done()
}
</script>

<style scoped>
.session-list-container {
  height: 100%;
  overflow-y: auto;
}

.session-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.session-item:hover {
  background-color: #f8f9fa;
}

.session-item.active {
  background-color: #e3f2fd;
  border-right: 3px solid #409eff;
}

.session-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #409eff;
}

.session-info {
  flex: 1;
  min-width: 0;
}

.session-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
  line-height: 1.4;
}

.session-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.message-count {
  font-weight: 400;
}

.last-time {
  font-weight: 400;
}

.session-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
  margin-left: 8px;
}

.session-item:hover .session-actions {
  opacity: 1;
}

.action-btn {
  padding: 4px;
  color: #909399;
}

.action-btn:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.empty-state {
  padding: 40px 16px;
  text-align: center;
}

.empty-state :deep(.el-empty__description p) {
  margin: 8px 0 0 0;
  font-size: 13px;
  color: #909399;
}

/* 对话框样式调整 */
:deep(.el-dialog__header) {
  padding: 20px 20px 10px 20px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 20px 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px 20px;
}
</style> 